<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>集装箱台账</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div id="takeoutMain">
      <a-form layout="inline" :model="form" style="margin-top:0px;">
        <a-form-item label="客户名称">
          <a-input v-model="form.custNameLike" />
        </a-form-item>
        <a-form-item label="公司编号/运单号/箱号">
          <a-input v-model="form.codeLike" />
        </a-form-item>
        <a-form-item label="船名/航次">
          <a-input v-model="form.nameLike" />
        </a-form-item>
        <a-form-item label="结算类型">
          <a-select v-model="form.settlementType" class="selectWidth">
            <a-select-option value>全部</a-select-option>
            <!-- <a-select-option :value="2">月结</a-select-option> -->
            <!-- <a-select-option :value="1">票结</a-select-option> -->
            <a-select-option v-for="v in settlementTypeList" :key="v.key">{{v.value}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属部门">
          <a-tree-select
            class="selectInputWidth"
            v-model="form.deptId"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :load-data="onLoadData"
            :tree-data="deptTreeData"
            placeholder="请选择"
            @change="onChangeTree"
          ></a-tree-select>
        </a-form-item>
        <a-form-item label="所属销售">
          <a-select v-model="form.sellerId" class="selectInputWidth">
            <a-select-option value>全部</a-select-option>
            <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-input-group compact>
            <a-select v-model="form.dateSearchType" style="width:110px">
              <a-select-option :value="1">创建日期</a-select-option>
              <a-select-option :value="2">装货时间</a-select-option>
            </a-select>
            <a-range-picker
              v-if="form.dateSearchType === 2"
              @change="timeChange"
              :show-time="{ format: 'HH:mm' }"
              format="YYYY-MM-DD HH:mm"
              style="width:300px"
            >
              <a-icon slot="suffixIcon" type="calendar" />
            </a-range-picker>
            <a-range-picker v-else @change="timeChange" style="width:300px">
              <a-icon slot="suffixIcon" type="calendar" />
            </a-range-picker>
          </a-input-group>
        </a-form-item>
        <a-form-item label="订单类型">
          <a-select v-model="form.orderType" class="selectWidth">
            <a-select-option value>全部</a-select-option>
            <a-select-option value="DOMESTIC_TRADE_EXPORTS">内贸出口订单</a-select-option>
            <a-select-option value="DOMESTIC_TRADE_IMPORTS">内贸进口订单</a-select-option>
            <a-select-option value="FOREIGN_TRADE_EXPORTS">外贸出口订单</a-select-option>
            <a-select-option value="FOREIGN_TRADE_IMPORTS">外贸进口订单</a-select-option>
            <a-select-option value="UNITED_TRANSPORT_EXPORTS">联运出口订单</a-select-option>
            <a-select-option value="UNITED_TRANSPORT_IMPORTS">联运进口订单</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="订单状态">
          <a-select v-model="form.status" class="selectWidth">
            <a-select-option value>全部</a-select-option>
            <a-select-option :value="1">进行中</a-select-option>
            <a-select-option :value="2">已完成</a-select-option>
            <a-select-option :value="3">已完成-异常</a-select-option>
            <a-select-option :value="4">已结算</a-select-option>
            <!-- <a-select-option :value="5">已作废</a-select-option> -->
          </a-select>
        </a-form-item>
        <a-form-item label="发货地址">
          <a-cascader
            :options="options"
            :fieldNames="{label: 'area', value: 'area', children: 'childList'}"
            placeholder="请选择省/市/区县"
            @change="addressChange"
          />
        </a-form-item>
        <a-form-item>
          <a-input placeholder="请输入详细地址" v-model="form.addressLike" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="check">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="excelExport">导出Excel</a-button>
        </a-form-item>
      </a-form>
      <a-card style="text-align:center; margin-top:24px;">
        <a-row :gutter="[16]">
          <a-col :span="6" class="assent">
            <div class="assent_mes">总订单数</div>
            <div class="assent_shu">{{statisticsObj.orderNum || 0}}</div>
          </a-col>
          <a-col :span="6" class="assent">
            <div class="assent_mes">总应收（元）</div>
            <div class="assent_shu">{{statisticsObj.receivableAmount || 0}}</div>
          </a-col>
          <a-col :span="6" class="assent">
            <div class="assent_mes">总应付（元）</div>
            <div class="assent_shu">{{statisticsObj.payableAmount || 0}}</div>
          </a-col>
          <a-col :span="6">
            <div class="assent_mes">总毛利（元）</div>
            <div class="assent_shu">{{statisticsObj.grossMargin || 0}}</div>
          </a-col>
        </a-row>
      </a-card>
      <a-table
        :columns="columns"
        :loading="loading"
        :data-source="data"
        style="margin-top:25px;"
        :scroll="{x:3500,y:600}"
        :pagination="pagination"
        :row-key="(record,index) => index"
      >
        <template slot="company" slot-scope="text, record">
          <a v-if="record.shipOrderCode" @click="orderDetail(record)">{{record.shipOrderCode}}</a>
          <span v-else>--</span>
        </template>
        <template slot="grossMargin" slot-scope="text, record">
          <span :style="record.grossMargin < 0 ? 'color:red': ''">{{record.grossMargin.toFixed(2)}}</span>
        </template>
        <template slot="status" slot-scope="text, record">
          <span v-if="record.status === 1">进行中</span>
          <span v-if="record.status === 2">已完成</span>
          <span v-if="record.status === 3">已完成-异常</span>
          <span v-if="record.status === 4">已结算</span>
          <span v-if="record.status === 5">已作废</span>
        </template>
        <template slot="settlementType" slot-scope="text, record">
          <span>{{checkSettlementTypeName(record.settlementType)}}</span>
        </template>
        <template slot="orderType" slot-scope="text, record">
          <span v-if="record.orderType === 'DOMESTIC_TRADE_EXPORTS'">内贸出口订单</span>
          <span v-if="record.orderType === 'DOMESTIC_TRADE_IMPORTS'">内贸进口订单</span>
          <span v-if="record.orderType === 'FOREIGN_TRADE_EXPORTS'">外贸出口订单</span>
          <span v-if="record.orderType === 'FOREIGN_TRADE_IMPORTS'">外贸进口订单</span>
          <span v-if="record.orderType === 'UNITED_TRANSPORT_EXPORTS'">联运出口订单</span>
          <span v-if="record.orderType === 'UNITED_TRANSPORT_IMPORTS'">联运进口订单</span>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script>
import {mixin} from '@/common/common'
import { querySellerDown, queryDeptDown, queryBaseAreaList } from '@/api'
import { queryContainerReportList, queryContainerReportListStatistics } from '@/api/dataBI'
import { commonExport } from '@/api/request'
const deptData = {
  type: 2, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL'
}
const sellerData = {
  type: 2, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL',
  status: 1
}
const columns = [
  {
    title: '序号',
    width: 80,
    customRender: (text, record, index) => {
      return index + 1
    }
  },
  {
    title: '公司编号',
    dataIndex: 'shipOrderCode',
    scopedSlots: {
      customRender: 'company'
    }
  },
  {
    title: '客户名称',
    dataIndex: 'custName',
    customRender: (text, record, index) => {
      return record.custName || '--'
    }
  },
  {
    title: '总毛利（元）',
    dataIndex: 'grossMargin',
    scopedSlots: {
      customRender: 'grossMargin'
    }
  },
  {
    title: '总应收金额（元）',
    dataIndex: 'receivableAmount',
    customRender: (text, record, index) => {
      return record.receivableAmount.toFixed(2) || '--'
    }
  },
  {
    title: '总应付金额（元）',
    dataIndex: 'payableAmount',
    customRender: (text, record, index) => {
      return record.payableAmount.toFixed(2) || '--'
    }
  },
  {
    title: '销售人员',
    dataIndex: 'seller',
    customRender: (text, record, index) => {
      return record.seller || '--'
    }
  },
  {
    title: '操作人员',
    dataIndex: 'handler',
    customRender: (text, record, index) => {
      return record.handler || '--'
    }
  },
  {
    title: '状态',
    _needName: true,
    dataIndex: 'status',
    scopedSlots: {
      customRender: 'status'
    }
  },
  {
    title: '订单类型',
    dataIndex: 'orderType',
    _needName: true,
    scopedSlots: {
      customRender: 'orderType'
    }
  },
  {
    title: '箱号',
    dataIndex: 'containerNo',
    customRender: (text, record, index) => {
      return record.containerNo || '--'
    }
  },
  {
    title: '箱型箱量',
    dataIndex: 'containerTypeName'
    // customRender: (text, record, index) => {
    //   return `${record.containerType}*1`
    // }
  },
  {
    title: '运单号',
    dataIndex: 'seagoingShipOrderCode',
    customRender: (text, record, index) => {
      return record.seagoingShipOrderCode || '--'
    }
  },
  {
    title: '订单创建日期',
    dataIndex: 'createDate',
    customRender: (text, record, index) => {
      return record.createDate || '--'
    }
  },
  {
    title: '结算类型',
    dataIndex: 'settlementType',
    _needName: true,
    scopedSlots: {
      customRender: 'settlementType'
    }
    // customRender: (text, record, index) => {
    //   return record.settlementType === 1 ? '票结' : '月结'
    // }
  },
  {
    title: '运输条款',
    dataIndex: 'transportTerms',
    customRender: (text, record, index) => {
      return record.transportTerms || '--'
    }
  },
  {
    title: '货名',
    dataIndex: 'goodsName',
    customRender: (text, record, index) => {
      return record.goodsName || '--'
    }
  },
  {
    title: '货重（吨）',
    dataIndex: 'goodsWeight',
    customRender: (text, record, index) => {
      return record.goodsWeight || '--'
    }
  },
  {
    title: '装货时间',
    dataIndex: 'loadingTime',
    customRender: (text, record, index) => {
      return record.loadingTime || '--'
    }
  },
  {
    title: '始发港',
    dataIndex: 'startPort',
    customRender: (text, record, index) => {
      return record.startPort || '--'
    }
  },
  {
    title: '目的港',
    dataIndex: 'endPort',
    customRender: (text, record, index) => {
      return record.endPort || '--'
    }
  },
  {
    title: '驳船船名航次',
    dataIndex: 'shipVoyageName'
    // customRender: (text, record, index) => {
    //   return `${record.shipName || '--'} / ${record.voyageNumber || '--'}`
    // }
  },
  {
    title: '海船船名航次',
    dataIndex: 'seagoingShipVoyageName'
    // customRender: (text, record, index) => {
    //   return `${record.seagoingShipName || '--'} / ${record.seagoingShipVoyage || '--'}`
    // }
  },
  {
    title: '发货地址',
    dataIndex: 'address',
    width: 220,
    ellipsis: true,
    customRender: (text, record, index) => {
      return record.address || '--'
    }
  }
]
export default {
  mixins: [mixin],
  data () {
    return {
      deptTreeData: [],
      sellers: [],
      options: [],
      form: {
        orderType: '',
        custNameLike: '', // 客户名称
        codeLike: '', // 公司编号/运单号/箱号
        nameLike: '', // 船名/航次
        settlementType: '', // 结算类型
        deptId: '', // 部门id
        dateSearchType: 1, // 时间类型 1、创建日期 2、装货日期
        startDate: '', // 开始日期
        endDate: '', // 结束日期
        status: '', // 订单状态 1进行中，2已完成，3已完成-异常，4已结算，5已作废
        province: '', // 省
        city: '', // 市
        area: '', // 县
        sellerId: '',
        addressLike: '' // 详细地址
      },
      pageNum: 1,
      pageSize: 10,
      loading: true,
      data: [],
      columns,
      pagination: {},
      btnControl: {},
      statisticsObj: {}
    }
  },
  methods: {
    queryContainerReportListStatisticsRequest (e) {
      queryContainerReportListStatistics(e).then(res => {
        let resData = res.data
        if (resData.grossMargin || resData.grossMargin === 0) resData.grossMargin = resData.grossMargin.toFixed(2)
        if (resData.receivableAmount || resData.receivableAmount === 0) resData.receivableAmount = resData.receivableAmount.toFixed(2)
        if (resData.payableAmount || resData.payableAmount === 0) resData.payableAmount = resData.payableAmount.toFixed(2)
        this.statisticsObj = resData
      })
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptDown({ parentId: treeNode.dataRef.key, ...deptData }).then(
          rsp => {
            let childrenData = []
            rsp.data.forEach(value => {
              childrenData.push({
                title: value.name,
                key: value.deptId,
                value: value.deptId
              })
            })
            treeNode.dataRef.children = childrenData
            this.deptTreeData = [...this.deptTreeData]
            resolve()
          }
        )
      })
    },
    initDept (e) {
      queryDeptDown(e).then(rsp => {
        let initData = []
        rsp.data.forEach((value, index) => {
          initData.push({
            title: value.name,
            key: value.deptId,
            value: value.deptId
          })
        })
        this.deptTreeData = initData
      })
    },
    onChangeTree (value) {
      this.initSellerDown(value)
    },
    initSellerDown (deptId) {
      querySellerDown({ ...sellerData, deptId }).then(rsp => {
        this.sellers = rsp.data.map((v, i) => {
          if (!v.uiId) {
            v.name = '请选择'
            v.uiId = ''
          }
          return v
        })
      })
    },
    queryAddressRequest (e) {
      queryBaseAreaList(e)
        .then(res => {
          this.options = res.data
        })
        .catch(rs => {})
    },
    containerListRequest (e) {
      this.loading = true
      queryContainerReportList(e)
        .then(res => {
          this.data = res.data.list
          let currentPage = this.pageNum
          this.pagination = {
            current: currentPage,
            pageSize: res.data.pageSize,
            total: res.data.total,
            showQuickJumper: false,
            showSizeChanger: true,
            pageSizeOptions: ['10', '30', '50', '100', '500'],
            showTotal: total =>
              `共${total}条记录 第${currentPage}/${res.data.pages}页`,
            onChange: pageNum => {
              this.pageNum = pageNum
              let paramData = {
                ...this.form,
                pageSize: this.pageSize,
                pageNum: this.pageNum
              }
              this.containerListRequest(paramData)
            },
            onShowSizeChange: (current, size) => {
              this.pageNum = current
              this.pageSize = size
              let paramData = {
                ...this.form,
                pageSize: this.pageSize,
                pageNum: this.pageNum
              }
              this.containerListRequest(paramData)
            }
          }
          this.loading = false
        })
        .catch(rs => {})
    },
    timeChange (date, dateString) {
      this.form.startDate = dateString[0]
      this.form.endDate = dateString[1]
    },
    addressChange (value, selectedOptions) {
      this.form.province = value[0]
      this.form.city = value[1]
      this.form.area = value[2]
    },
    orderDetail (e) {
      window.open(`/orderCenter/order/detail/${e.shipOrderId}`, '_blank')
    },
    check () {
      this.pageNum = 1
      this.containerListRequest({
        ...this.form,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
      this.queryContainerReportListStatisticsRequest({
        ...this.form
      })
    },
    excelExport () {
      commonExport('/containerReport/exportContainerReportList', {
        ...this.form,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: this.columns
      })
    }
  },
  mounted () {
    this.initDept(deptData) // 所属部门
    this.initSellerDown() // 所属销售
    this.queryAddressRequest({})
    this.containerListRequest({
      ...this.form,
      pageNum: this.pageNum,
      pageSize: this.pageSize
    })
    this.queryContainerReportListStatisticsRequest({
      ...this.form
    })
    this.$nextTick(() => {
      this.btnControl = this.$root._bc
      // // console.log(this.$root._bc)
    })
  }
}
</script>

<style lang="less" scoped>
#takeoutMain {
  padding: 24px;
  margin: 24px;
  background: #fff;
  min-height: 700px;
}
</style>
